<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        body {
            margin: 0px;
            padding: 0px;
        }

        div {
            width: 100px;
            height: 100px;
            background-color: #ff0000;
            position: relative;
            top: 50px;
        }

        #box2 {
            background-color: #aaffaa;

        }
    </style>
</head>
<body>
<input type="button" id="but1" value="到400">
<input type="button" id="but2" value="到800">
<div id="box">

</div>
<div id="box2">

</div>
</body>
<script>
    var but1 = document.getElementById('but1');
    var but2 = document.getElementById('but2');
    var box = document.getElementById('box');
    // var timer = null;

    function animate(target,ele,move,time) {
        clearInterval(ele.timer);//每一次启动函数都清除一边计时器
       ele.timer = setInterval(function () {//把计时器的返回值设置在当前控制元素的属性中，规避控制多个元素时在前面执行的计时器被后面覆盖的BUG
           var buchang = ele.offsetLeft;//设置接收元素的实时位置
           var step = target > buchang ? move : -move;//每次执行的移动距离，设置返回加上判断
           buchang += step;//计算移动，实时边距加每次移动步长，实现动态移动
           if (Math.abs(target-buchang) > Math.abs(step)) {//判断剩余的移动距离是否足够执行一次步长
               ele.style.left = buchang +'px';//如果够步长执行一次則直接赋值给Left
           } else {
               ele.style.left = target +'px';//如果不够步长执行一次则直接赋值target
               clearInterval(ele.timer);//执行完毕，清除一边计时器
           }
       },time)
    }
    but1.onclick = function () {
        animate(400,box,5,80);
        animate(400,box2,5,80);
    };
    but2.onclick = function () {
        animate(800,box,5,80);
        animate(800,box2,5,80);
    };

</script>
</html>